import axios from 'axios'
import { getToken, removeToken } from '@/utils/auth.js'
import { useUserStore } from '@/store/modules/user.js'
import { ElMessage } from 'element-plus'
import router from '@/router'

// 用于防止重复提示
let isTokenExpired = false
// 用于存储当前的退出登录Promise
let logoutPromise = null

const request = axios.create({
  baseURL: import.meta.env.VITE_BASE_API,
  timeout: 10000,
})

// 请求拦截器
request.interceptors.request.use((config) => {
  const token = getToken()
  if (token) {
    config.headers.Authorization = token
  }
  return config
})

// 响应拦截器
request.interceptors.response.use(
  (response) => {
    if (response.data.code === 2) {
      // 登录失效
      if (!isTokenExpired) {
        isTokenExpired = true

        // 如果已经在处理退出登录，则返回现有的Promise
        if (logoutPromise) {
          return logoutPromise
        }

        // 创建新的退出登录Promise
        logoutPromise = new Promise((resolve, reject) => {
          ElMessage.error('登录已过期，请重新登录')

          // 先清除token
          removeToken()

          // 获取store实例并执行登出
          const userStore = useUserStore()
          userStore.logout()

          // 跳转到登录页
          router.replace('/login')

          // 3秒后重置状态
          setTimeout(() => {
            isTokenExpired = false
            logoutPromise = null
          }, 3000)

          reject(new Error('登录已过期'))
        })

        return logoutPromise
      }
      return Promise.reject(new Error('登录已过期'))
    }

    if (response.data.code === 0) {
      // ElMessage.error(response.data.msg)
      return Promise.reject(new Error(response.data.msg))
    }
    return response.data
  },
  (error) => {
    // 避免在token过期时显示额外的错误信息
    if (!isTokenExpired) {
      ElMessage.error(error.message || '请求失败')
    }
    return Promise.reject(error)
  }
)

export default request
